from django.core.cache import cache
from django.core.cache.backends.db import DatabaseCache
from django.core.paginator import Paginator
from django.core.serializers.json import DjangoJSONEncoder
from django.core.serializers import serialize, deserialize
from django.db.models import QuerySet


class LazyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        # if isinstance(obj, ):
        #     return str(obj)
        return super().default(obj)


def dbCache() -> DatabaseCache:
    return cache


def json_serialize(queryset):
    return serialize('json', queryset=queryset, cls=LazyEncoder)


def json_deserialize(string):
    return deserialize('json', string, ignorenonexistent=True)


def api_data(data, message='success', code=200, pager=None):
    if isinstance(data, QuerySet):
        data = list(data)
    wrapper = {'code': code, 'message': message, 'data': list(data)}
    if isinstance(pager, Paginator):
        wrapper['paging'] = {'num_pages': pager.num_pages, 'per_page': pager.per_page, 'count': pager.count}
    return wrapper


Cache = dbCache()
